﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data;

namespace CodeFarmer.DataAccess.Infrastructure
{
    public abstract class BaseRepository<T> where T : class
    {
        private CodeFarmerContext db;
        private readonly IDbSet<T> dbset;

        protected IDbFactory DbFactory
        {
            get;
            private set;
        }

        protected CodeFarmerContext DB
        {
            get
            {
                return db ?? (db = DbFactory.GetDb());
            }
        }

        public BaseRepository(IDbFactory dbFactory)
        {
            this.DbFactory = dbFactory;
            this.dbset = DB.Set<T>();
        }

        public virtual void Add(T entity)
        {
            dbset.Add(entity);
        }

        public virtual void Delete(T entity)
        {
            dbset.Remove(entity);
        }

        public virtual void Update(T entity)
        {
            dbset.Attach(entity);
            db.Entry(entity).State = EntityState.Modified;
        }

        public virtual T GetById(long Id)
        {
            return dbset.Find(Id);
        }

        public virtual T GetById(string Id)
        {
            return dbset.Find(Id);
        }
    }
}
